package com.bootdo.wx.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaShopOrderService;
import cn.binarywang.wx.miniapp.api.WxMaShopSpuService;
import cn.binarywang.wx.miniapp.api.impl.WxMaShopOrderServiceImpl;
import cn.binarywang.wx.miniapp.api.impl.WxMaShopSpuServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.shop.*;
import cn.binarywang.wx.miniapp.bean.shop.request.WxMaShopOrderPayRequest;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaShopAddOrderResponse;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.bootdo.common.config.WxMaConfiguration;
import com.bootdo.common.config.WxMaProperties;
import com.bootdo.common.utils.*;
import com.bootdo.wx.constant.Constants;
import com.bootdo.wx.dao.*;
import com.bootdo.wx.domain.*;
import com.bootdo.wx.service.*;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by HP on 2019/7/13.
 */
@Controller
@RequestMapping("/api/wxPay")
public class ApiWeChatPayController {

    @Autowired
    private SetWechatService setWechatService;
    @Autowired
    private OrderOrderService orderOrderService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private OrderComService orderComService;
    @Autowired
    private MemberPriceService memberPriceService;
    @Autowired
    private WeChatPayService weChatPayService;
    @Autowired
    private WxMaProperties properties;
    @Autowired
    private CmsNoticeDao cmsNoticeDao;
    @Autowired
    private OrderShippingDao orderShippingDao;
    @Autowired
    private GoodsGoodsDao goodsGoodsDao;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private MemberCouponDao memberCouponDao;
    @Autowired
    private GoodsProductDao goodsProductDao;


    private final Logger log = LoggerFactory.getLogger(this.getClass());



    /**
     * 微信下单支付接口
     *
     * @param params
     * @param req
     * @return
     */
    @RequestMapping("/pay")
    @ResponseBody
    public R pay(@RequestBody Map<String, Object> params, HttpServletRequest req) {
        try {
//            log.debug("map::" + Json.toJson(map));
            /*if (!params.containsKey("payNum") || params.get("payNum").toString().isEmpty()
                    ||!params.containsKey("userId") || params.get("userId").toString().isEmpty()
                    ||!params.containsKey("payment") || params.get("payment").toString().isEmpty()
                    ) {
                return R.error(100, "参数错误");
            }*/

           /* if( params.containsKey("payNum")&&null!=params.get("payNum")&&!"".equals(params.get("payNum"))){
                String payNum = params.get("payNum").toString();

            }*/
            String userId = params.get("userId").toString();
            //OrderOrderDO order = orderOrderService.get(orderId);
           /* if (order == null) {
                return R.error(101, "订单异常");
            }*/
            MemberUserDO userDO = memberUserService.get(userId);
            if (userDO == null) {
                return R.error(103, "用户异常");
            }
            SetWechatDO setWechatDO = setWechatService.list(new HashMap<String, Object>()).get(0);
            SortedMap<String, String> signMap = new TreeMap<>();


            signMap.put("body", "商品"); //商品描述  必

            //signMap.put("appId", goods.getIntro()); //应用ID  必
            //signMap.put("mch_id", goods.getGoodsName()); //商户号  必
            //signMap.put("sign_type", "MD5"); //签名类型默认MD5
            //signMap.put("notify_url", order.getTotalAmount()); //通知地址 回调url  必
            //signMap.put("trade_type", "APP"); //交易类型  APP 必
            //signMap.put("time_start", order.getTotalAmount()); //交易开始时间  必
            //signMap.put("time_expire", order.getTotalAmount()); //交易结束时间    大于5分钟
            //signMap.put("nonce_str", order.getOrderSn()); //随机字符串  必

//            signMap.put("body", goods.getGoodsName()); //商品描述  必
            signMap.put("attach", "商品"); //商品详情  非
            signMap.put("openid", userDO.getWechatOpenId()); //小程序支付必填，其他非填

            int total_fee=0;
            if( params.containsKey("payNum")&&null!=params.get("payNum")&&!"".equals(params.get("payNum"))){
                String payNum = params.get("payNum").toString();
                signMap.put("out_trade_no", payNum); //商户订单号  必
                total_fee  = Math.round(Float.valueOf(new BigDecimal(MapUtil.getStr(params,"payment")).multiply(new BigDecimal(100)).toString()));

            }else{

                OrderOrderDO orderOrderDO = orderOrderService.get(MapUtil.getStr(params, "orderId"));
                signMap.put("out_trade_no", orderOrderDO.getPayNum());
                total_fee  = Math.round(Float.valueOf(orderOrderDO.getPayment().multiply(new BigDecimal(100)).toString()));

            }

            /*float sessionmoney = Float.parseFloat(order.getPayment().toString());
            String finalmoney = String.format("%.2f", sessionmoney);
            finalmoney = finalmoney.replace(".", "");
            String newStr = finalmoney.replaceFirst("^0*", "");*/
            

            signMap.put("total_fee", String.valueOf(total_fee)); //总金额  必    /分
           // signMap.put("total_fee", "1");    //先支付1分
            signMap.put("spbill_create_ip", StringUtils.getRemoteAddr(req)); //终端ip  用户端ip  必
            signMap.put("notify_url",setWechatDO.getUrl() + "/api/wxPay/weixinpayNotify");
            Map<String,Object> map = WeChatPayUtils.getOrderSignature(signMap,setWechatDO);

            //视频号支付
            map.putAll(params);
            videoPay(map);


            return R.ok().put("data", map);
        } catch (Exception e) {
            return R.error("微信支付失败!");
        }
    }

    /**
     * 余额支付
     */
    @PostMapping("/pricePay")
    @ResponseBody
    public R pricePay(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                || !params.containsKey("orderId") || !params.containsKey("orderId")
                ){
            return R.error("参数异常");
        }
        try{
            String orderId = params.get("orderId").toString();
            String userId = params.get("userId").toString();
            OrderOrderDO order = orderOrderService.get(orderId);
            if (order == null) {
                return R.error(101, "订单异常");
            }
            MemberUserDO userDO = memberUserService.get(userId);
            if (userDO == null) {
                return R.error(103, "用户异常");
            }
            Map<String,Object> moneyMap = orderComService.getMemberCom(params);
            BigDecimal allPrice = new BigDecimal(moneyMap.get("allPrice").toString());   //余额
            BigDecimal payment = order.getPayment();
            if (allPrice.compareTo(payment) == -1) {
                return R.error("余额不足，请充值");
            }
            params.put("payType", "2");
            return orderOrderService.pricePay(params);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }


    /*微信下单支付回调*/
    @ResponseBody
    @RequestMapping("/weixinpayNotify")
    public void weixinpayNotify(HttpServletRequest req, HttpServletResponse res) {
        try {
            InputStream inStream = req.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map<Object, Object> mapFromXml = PayCommonUtil.doXMLParse(result);
            log.error("mapFromXml::" + mapFromXml.toString());
            SortedMap<String ,String > sortedMap = new TreeMap();
            log.error("map001::");
            if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {

                log.error("微信支付成功::");
                // 告诉微信服务器，我收到信息了，不要在调用回调action了
                sortedMap.put("return_code","SUCCESS");
                sortedMap.put("return_msg","OK");
                res.getWriter().write(parseXML(sortedMap));

                log.error("map004::开始订单处理");
                List<OrderOrderDO> orderList =  orderOrderService.getByPayNum(mapFromXml.get("out_trade_no").toString());
                if(orderList.size()>0){
                    //OrderOrderDO order = orderOrderService.getByOrder(mapFromXml.get("out_trade_no").toString());
                    for (OrderOrderDO order : orderList) {


                        if (order.getStatus() == 1) {
                            log.error("map003::" + order.toString());
                            if (verifyWeixinNotify(mapFromXml)) {

                                //订单处理
                                Map<String,Object> priceMap = new HashMap<String,Object>();
                                priceMap.put("userId",order.getUserId());
                                priceMap.put("orderId",order.getId());
                                priceMap.put("payType", "0");
                                R r = orderOrderService.pricePay(priceMap);
                                System.out.println("!!!!!!!!!!!!!!!!!"+r);
                                OrderShippingDO byOrderId = orderShippingDao.getByOrderId(order.getId());
                                try {
                                    //同步视频号支付成功信息
                                    MemberUserDO memberUserDO = memberUserService.get(order.getUserId());
                                    final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
                                    WxMaShopOrderService wxMaShopOrderService = new WxMaShopOrderServiceImpl(wxService);
                                    WxMaShopOrderPayRequest wxMaShopOrderPayRequest = new WxMaShopOrderPayRequest();
                                    wxMaShopOrderPayRequest.setPayTime(DateUtil.format(order.getPayAt(),DateUtils.DATE_TIME_PATTERN));
                                    wxMaShopOrderPayRequest.setOpenid(memberUserDO.getWechatOpenId());
                                    wxMaShopOrderPayRequest.setOutOrderId(order.getId());
                                    wxMaShopOrderPayRequest.setTransactionId(order.getPayNum());
                                    wxMaShopOrderPayRequest.setActionType(1);
                                    wxMaShopOrderService.orderPay(wxMaShopOrderPayRequest);
                                    //支付成功提醒
                                    //发送订阅消息
                                    //final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
                                    WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();

                                    subscribeMessage.setToUser(memberUserDO.getWechatOpenId());
                                    subscribeMessage.setTemplateId(Constants.mesage.MODE_ORDER_PAY);
                                    subscribeMessage.setPage(Constants.mesage.address.ADDRESS_ORDER_INFO+"?id="+order.getId());

                                    List<WxMaSubscribeMessage.Data> list = new ArrayList<>();
                                    for (int i = 0; i < 5; i++) {
                                        WxMaSubscribeMessage.Data data = new WxMaSubscribeMessage.Data();
                                        switch (i) {
                                            case 0:
                                                data.setName("character_string2");
                                                data.setValue(order.getOrderSn());
                                                break;
                                            case 1:
                                                data.setName("amount3");
                                                data.setValue(order.getPayment()+"");
                                                break;
                                            case 2:
                                                data.setName("date4");
                                                data.setValue(DateUtil.format(order.getCreateAt(),DateUtils.DATE_TIME_PATTERN));
                                                break;
                                            case 3:
                                                data.setName("date8");
                                                data.setValue(DateUtil.format(new Date(),DateUtils.DATE_TIME_PATTERN));
                                                break;
                                            case 4:
                                                data.setName("thing17");
                                                //+",地址:"+byOrderId.getReceiverCity()+","+byOrderId.getReceiverTown()+","+byOrderId.getShopAddress()
                                                data.setValue(byOrderId.getReceiverName()+" "+byOrderId.getReceiverPhone());
                                                break;
                                            default:
                                                break;
                                        }
                                        list.add(data);


                                    }
                                    subscribeMessage.setData(list);
                                    wxService.getMsgService().sendSubscribeMsg(subscribeMessage); //发送订阅消息
                                } catch (WxErrorException e) {
                                    e.printStackTrace();

                                }
                                List<Map<String, Object>> goodsDetail = orderDetailDao.getByOrderId(order.getId());
                                GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(MapUtil.getStr(goodsDetail.get(0), "goodId"));
                                //往平台公告表加入数据
                                CmsNoticeDO cmsNoticeDO = new CmsNoticeDO();
                                cmsNoticeDO.setId(IdUtil.simpleUUID());
                                cmsNoticeDO.setContent("您购买的"+goodsGoodsDO.getName()+"*"+MapUtil.getStr(goodsDetail.get(0), "total")+"的订单已支付成功!订单号为"+order.getOrderSn()+".收货人:"+byOrderId.getReceiverName()+"收货人手机号:"+byOrderId.getReceiverPhone()+"收货地址:"+byOrderId.getReceiverProvince()+","+byOrderId.getReceiverCity()+","+byOrderId.getReceiverCity()+","+byOrderId.getReceiverTown()+","+byOrderId.getShopAddress()+"!");
                                cmsNoticeDO.setDelFlag(0);
                                cmsNoticeDO.setCaAt(new Date());
                                cmsNoticeDO.setTitle("支付通知");
                                cmsNoticeDO.setUserId(order.getUserId());
                                cmsNoticeDao.save(cmsNoticeDO);

                                /*log.error("map005::");
                                if (r.get("msg").toString().equals("0")) {
                                    log.error("微信支付成功::");
                                    // 告诉微信服务器，我收到信息了，不要在调用回调action了
                                    sortedMap.put("return_code","SUCCESS");
                                    sortedMap.put("return_msg","OK");
                                    res.getWriter().write(parseXML(sortedMap));

                                } else {
                                    log.error("微信支付失败，数据更新失败");
                                }*/

                            }else{
                                log.error("map011::");
                                sortedMap.put("return_code","FAIL");
                                sortedMap.put("return_msg","签名失败");
                                res.getWriter().write(parseXML(sortedMap));
                            }
                    }

                }







                    log.error("map012::");
                } else {
                    log.error("map013::订单已经修改过了");
                }
            }
            log.error("map012::");
            //return "success";
        } catch (Exception e) {
            System.out.println("支付发生错误");

            //return "failure";
        }
    }

    /**
     * 微信充值接口
     *
     * @param params
     * @param req
     * @return
     */
    @RequestMapping("/payTwo")
    @ResponseBody
    public R payTwo(@RequestBody Map<String, Object> params, HttpServletRequest req) {
        try {
//            log.debug("map::" + Json.toJson(map));
            if (!params.containsKey("money") || params.get("money").toString().isEmpty()
                    ||!params.containsKey("userId") || params.get("userId").toString().isEmpty()
                    ) {
                return R.error(100, "参数错误");
            }
            BigDecimal money = new BigDecimal(params.get("money").toString());
            String userId = params.get("userId").toString();
            MemberUserDO userDO = memberUserService.get(userId);
            if (userDO == null) {
                return R.error(103, "用户异常");
            }
            SetWechatDO setWechatDO = setWechatService.list(new HashMap<String, Object>()).get(0);
            SortedMap<String, String> signMap = new TreeMap<>();
            //插入充值记录
            MemberPriceDO priceDO = new MemberPriceDO();
            priceDO.setId(UuidUtil.get32UUID());
            priceDO.setType(2);
            priceDO.setUserId(userId);
            priceDO.setPrice(money);
            priceDO.setDelFlag(1);
            priceDO.setCreateAt(new Date());
            priceDO.setUpdateAt(new Date());
            memberPriceService.save(priceDO);

            signMap.put("body", "商品"); //商品描述  必

            //signMap.put("appId", goods.getIntro()); //应用ID  必
            //signMap.put("mch_id", goods.getGoodsName()); //商户号  必
            //signMap.put("sign_type", "MD5"); //签名类型默认MD5
            //signMap.put("notify_url", order.getTotalAmount()); //通知地址 回调url  必
            //signMap.put("trade_type", "APP"); //交易类型  APP 必
            //signMap.put("time_start", order.getTotalAmount()); //交易开始时间  必
            //signMap.put("time_expire", order.getTotalAmount()); //交易结束时间    大于5分钟
            //signMap.put("nonce_str", order.getOrderSn()); //随机字符串  必

//            signMap.put("body", goods.getGoodsName()); //商品描述  必
            signMap.put("attach", "充值"); //商品详情  非
            signMap.put("openid", userDO.getWechatOpenId()); //小程序支付必填，其他非填
            signMap.put("out_trade_no", priceDO.getId()); //商户订单号  必
            /*float sessionmoney = Float.parseFloat(order.getPayment().toString());
            String finalmoney = String.format("%.2f", sessionmoney);
            finalmoney = finalmoney.replace(".", "");
            String newStr = finalmoney.replaceFirst("^0*", "");*/
            int total_fee  = Math.round(Float.valueOf(money.multiply(new BigDecimal(100)).toString()));
            signMap.put("total_fee", String.valueOf(total_fee)); //总金额  必    /分
            /*signMap.put("total_fee", "1");  //先支付1分*/
            signMap.put("spbill_create_ip", StringUtils.getRemoteAddr(req)); //终端ip  用户端ip  必
            signMap.put("notify_url",setWechatDO.getUrl() + "/api/wxPay/weixinpayTwoNotify");
            Map<String,Object> map = WeChatPayUtils.getOrderSignature(signMap,setWechatDO);

//            log.debug("weixin sign=="+wxorder);

//            logService.async(Mp_log.c(map.getString("appId"), map.getString("appSecret"), "", "user.weixinPay", "微信支付", "微信支付"));
            return R.ok().put("data", map);
        } catch (Exception e) {
            return R.error("微信支付失败!");
        }
    }

    /*微信充值回调*/
    @ResponseBody
    @RequestMapping("/weixinpayTwoNotify")
    public Object weixinpayTwoNotify(HttpServletRequest req, HttpServletResponse res) {
        try {
            InputStream inStream = req.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            System.out.println("~~~~~~~~~~~~~~~~充值成功~~~~~~~~~");
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map<Object, Object> mapFromXml = PayCommonUtil.doXMLParse(result);
            log.error("chongzhiFromXml::" + mapFromXml.toString());
            SortedMap<String ,String > sortedMap = new TreeMap();
            log.error("chongzhi001::");
            if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
                log.error("chongzhi002::");
                String priceId = mapFromXml.get("out_trade_no").toString();
                MemberPriceDO priceDO = memberPriceService.get(priceId);
                if (priceDO.getDelFlag() == 1) {
                    log.error("chongzhi003::priceId:" + priceId);
                    if (verifyWeixinNotify(mapFromXml)) {
                        log.error("chongzhi004::开始充值处理");
                        //订单处理
                        int o = memberPriceService.czSuccse(priceId);
                        log.error("chongzhi005::" + o);
                        if (o == 0) {
                            log.error("微信充值成功::");
                            // 告诉微信服务器，我收到信息了，不要在调用回调action了
                            sortedMap.put("return_code","SUCCESS");
                            sortedMap.put("return_msg","OK");
                            res.getWriter().write(parseXML(sortedMap));

                        }
                        log.error("微信充值失败，数据更新失败");
                    }else{
                        log.error("chongzhi011::");
                        sortedMap.put("return_code","FAIL");
                        sortedMap.put("return_msg","签名失败");
                        res.getWriter().write(parseXML(sortedMap));
                    }
                    log.error("map012::");
                } else {
                    log.error("map013::这笔充值已经处理过了");
                }

            }
            log.error("map012::");
            return "success";
        } catch (Exception e) {
            return "failure";
        }
    }


    public boolean verifyWeixinNotify(Map<Object, Object> map) {
        SetWechatDO setWechatDO = setWechatService.list(new HashMap<String, Object>()).get(0);
        SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
        String sign = (String) map.get("sign");
        for (Object keyValue : map.keySet()) {
            if(!keyValue.toString().equals("sign")){
                parameterMap.put(keyValue.toString(), map.get(keyValue));
            }
        }
        String createSign = PayCommonUtil.createSign("UTF-8", parameterMap,setWechatDO.getKey());
        if(createSign.equals(sign)){
            return true;
        }else{
            return false;
        }

    }

    //输出XML
    public String parseXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>\n");
        Set es = map.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(null != v && !"".equals(v) && !"appkey".equals(k)) {

                sb.append("<" + k +">" + v + "</" + k + ">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    //具体的调用微信的退款接口
    @ResponseBody
    @RequestMapping("/refund")
    public R refund(Map<String,Object> params) throws Exception{
        if (!params.containsKey("orderId") || params.get("orderId").toString().isEmpty()
                ) {
            return R.error(100, "参数错误");
        }
        return weChatPayService.refund(params);
    }


    /**
     * 视频号支付
     * @param map
     */
    public void videoPay(Map<String,Object> map){
        System.out.println("同步视频号支付订单");

        int total_fee=0;
        if( map.containsKey("payNum")&&null!=map.get("payNum")&&!"".equals(map.get("payNum"))){
            String payNum = map.get("payNum").toString();
            map.put("out_trade_no", payNum); //商户订单号  必

            total_fee  = Math.round(Float.valueOf(new BigDecimal(MapUtil.getStr(map,"payment")).multiply(new BigDecimal(100)).toString()));

            List<OrderOrderDO> byPayNum = orderOrderService.getByPayNum(payNum);
            for (OrderOrderDO orderOrderDO : byPayNum) {
                map.put("orderId",orderOrderDO.getId());
                addOrder(map);
            }

        }else{
            map.put("out_trade_no", MapUtil.getStr(map,"orderId"));
            OrderOrderDO orderOrderDO = orderOrderService.get(MapUtil.getStr(map, "orderId"));
            total_fee  = Math.round(Float.valueOf(orderOrderDO.getPayment().multiply(new BigDecimal(100)).toString()));
            addOrder(map);
        }

    }
    //视频号相关
    public void addOrder(Map<String,Object> map){
        try {

            MemberUserDO memberUserDO = memberUserService.get(MapUtil.getStr(map, "userId"));
            String orderId = MapUtil.getStr(map, "orderId");
            OrderShippingDO orderShippingDO = orderShippingDao.getByOrderId(orderId); //物流
            OrderOrderDO orderOrderDO = orderOrderService.get(orderId); //订单
            List<Map<String, Object>> orderDetalList = orderDetailDao.getByOrderId(orderId); //订单详情
            GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(orderDetalList.get(0).get("goodId").toString()); //商品
            int total = MapUtil.getInt(orderDetalList.get(0), "total"); //总数
            String productId = MapUtil.getStr(orderDetalList.get(0), "productId"); //产品id
            GoodsProductDO goodsProductDO = goodsProductDao.get(productId); //产品


            //优惠金额
            BigDecimal couponPrice =new BigDecimal("0.00");
            if(StringUtils.isNotBlank(orderOrderDO.getCouponId())){
                MemberCouponDO memberCouponDO = memberCouponDao.get(orderOrderDO.getCouponId());
                couponPrice=memberCouponDO.getMoney();
            }



            final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
            WxMaShopSpuService wxMaShopSpuService = new WxMaShopSpuServiceImpl(wxService);

            WxMaShopOrderService wxMaShopOrderService = new WxMaShopOrderServiceImpl(wxService);
            WxMaShopOrderInfo wxMaShopOrderInfo = new WxMaShopOrderInfo();
            wxMaShopOrderInfo.setCreateTime(DateUtil.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            wxMaShopOrderInfo.setOutOrderId(orderId);
            wxMaShopOrderInfo.setOpenid(memberUserDO.getWechatOpenId());
            wxMaShopOrderInfo.setOutUserId(memberUserDO.getId());
            wxMaShopOrderInfo.setPath(Constants.mesage.address.ADDRESS_ORDER_INFO+"?id="+orderId);
            //收货地址相关
            WxMaShopAddressInfo wxMaShopAddressInfo = new WxMaShopAddressInfo();
            wxMaShopAddressInfo.setCity(orderShippingDO.getReceiverCity());
            wxMaShopAddressInfo.setProvince(orderShippingDO.getReceiverProvince());
            wxMaShopAddressInfo.setTown(orderShippingDO.getReceiverCounty());
            wxMaShopAddressInfo.setDetailedAddress(orderShippingDO.getReceiverAddress());
            wxMaShopAddressInfo.setReceiverName(orderShippingDO.getReceiverName());
            wxMaShopAddressInfo.setTelNumber(orderShippingDO.getReceiverPhone());
            wxMaShopOrderInfo.setAddressInfo(wxMaShopAddressInfo);
            //物流相关
            WxMaShopOrderDetail wxMaShopOrderDetail = new WxMaShopOrderDetail();
            WxMaShopDeliveryDetail wxMaShopDeliveryDetail = new WxMaShopDeliveryDetail();
            //WxMaShopDeliveryItem wxMaShopDeliveryItem = new WxMaShopDeliveryItem();
            //wxMaShopDeliveryItem.setDeliveryId();
            //wxMaShopDeliveryDetail.setDeliveryList();
            wxMaShopDeliveryDetail.setDeliveryType(1); //// 1: 正常快递, 2: 无需快递, 3: 线下配送, 4: 用户自提
            //wxMaShopDeliveryDetail.setFinishAllDelivery(1);
            wxMaShopOrderDetail.setDeliveryDetail(wxMaShopDeliveryDetail);

            wxMaShopOrderInfo.setDeliveryDetail(wxMaShopDeliveryDetail);
            //支付相关
            WxMaShopPayInfo wxMaShopPayInfo = new WxMaShopPayInfo();
            wxMaShopPayInfo.setPayMethod("微信支付");
            wxMaShopPayInfo.setPayTime(DateUtil.format(new Date(),DateUtils.DATE_TIME_PATTERN));
            wxMaShopPayInfo.setPrepayId(MapUtil.getStr(map,"prepayId"));
            wxMaShopPayInfo.setPrepayTime(DateUtil.format(new Date(),DateUtils.DATE_TIME_PATTERN));
            wxMaShopPayInfo.setTransactionId(orderOrderDO.getPayNum());//订单号 order_sn 或者 payNum
            List<WxMaShopPayInfo> list = new ArrayList<>();
            list.add(wxMaShopPayInfo);
            wxMaShopOrderDetail.setMultiPayInfo(list);
            wxMaShopOrderDetail.setPayInfo(wxMaShopPayInfo);

            //金额相关  // 注意价格字段的单价是分，不是元
            WxMaShopPriceInfo wxMaShopPriceInfo = new WxMaShopPriceInfo();
            wxMaShopPriceInfo.setAdditionalPrice( Math.round(Float.valueOf(orderOrderDO.getPostInsurance().multiply(new BigDecimal(100)).toString())));//附加金额
            wxMaShopPriceInfo.setAdditionalRemarks("运险费");
            wxMaShopPriceInfo.setDiscountedPrice( Math.round(Float.valueOf(couponPrice.multiply(new BigDecimal(100)).toString())));//优惠金额
            wxMaShopPriceInfo.setOrderPrice(Math.round(Float.valueOf(orderOrderDO.getPayment().multiply(new BigDecimal(100)).toString())));
            wxMaShopPriceInfo.setFreight(Math.round(Float.valueOf(orderOrderDO.getPostFee().multiply(new BigDecimal(100)).toString())));

            wxMaShopOrderDetail.setPriceInfo(wxMaShopPriceInfo);

            //商品相关
            WxMaShopProductInfo wxMaShopProductInfo = new WxMaShopProductInfo();
            wxMaShopProductInfo.setOutProductId(goodsGoodsDO.getId());
            wxMaShopProductInfo.setPath(Constants.mesage.address.ADDRESS_GOODS_INFO+"?id="+goodsGoodsDO.getId());
            wxMaShopProductInfo.setProductCnt(total);
            wxMaShopProductInfo.setHeadImg(goodsGoodsDO.getImgurl());
            wxMaShopProductInfo.setOutSkuId(productId);
            wxMaShopProductInfo.setSalePrice(Math.round(Float.valueOf(goodsProductDO.getPrice().multiply(new BigDecimal(100)).toString())));  //生成这次订单时商品的售卖价，可以跟上传商品接口的价格不一致
            wxMaShopProductInfo.setTitle(goodsGoodsDO.getTitle());
            List<WxMaShopProductInfo> productInfoList = new ArrayList<>();
            productInfoList.add(wxMaShopProductInfo);

            wxMaShopOrderDetail.setProductInfos(productInfoList);


            wxMaShopOrderInfo.setOrderDetail(wxMaShopOrderDetail);
            WxMaShopAddOrderResponse wxMaShopAddOrderResponse = wxMaShopOrderService.addOrder(wxMaShopOrderInfo);
            System.out.println("errcode:"+wxMaShopAddOrderResponse.getErrcode());
            System.out.println("wxMaShopAddOrderResponse:"+wxMaShopAddOrderResponse.toString());
             /*检查场景值是否在支付校验范围内
            Boolean aBoolean = wxMaShopOrderService.checkScene(1177);
            System.out.println("aBoolean:"+aBoolean);*/
        } catch (WxErrorException e) {
            e.printStackTrace();
            System.out.println(e.getLocalizedMessage());

        }
    }



}
